mod proxy_http_1;
mod test;
mod proxy_http_2;
mod kv;
mod StdStreamCopy;

use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use std::borrow::BorrowMut;
use crate::proxy_http_1::Proxy;
use std::thread;

// #[tokio::main]
// //成功端口转发
// async fn main() -> Result<(), Box<dyn std::error::Error>> {
//     let listener = TcpListener::bind("127.0.0.1:9988").await?;
//     loop {
//         let (mut sk, _) = listener.accept().await?;
//         tokio::spawn(async move {
//             let mut st = TcpStream::connect("127.0.0.1:1000").await.expect("cant open");
//             let mut sk0 = TcpStream::into_std(sk).expect("into std fail");
//             let mut st0 = TcpStream::into_std(st).expect("into std fail");
//             let mut sk1 = sk0.try_clone().expect("clone fail");
//             let mut st1 = st0.try_clone().expect("clone fail");
//
//
//             let t1 = thread::spawn(move || {
//                 let mut copier = StdStreamCopy::Copier::new();
//                 copier.cp(&mut sk0, &mut st0);
//             });
//             let mut copier = StdStreamCopy::Copier::new();
//             copier.cp(&mut st1, &mut sk1);
//             t1.join();
//         });
//     }
// }
fn main() {
    let mut proxy = Proxy::new("0.0.0.0:3128").unwrap();
    proxy.run();
}

async fn copy(s1: &mut TcpStream, s2: &mut TcpStream) {
    loop {
        let mut buf = [0; 4096];
        let n = match s1.read(&mut buf).await {
            // socket closed
            Ok(n) if n == 0 => return,
            Ok(n) => n,
            Err(e) => {
                eprintln!("failed to read from socket; err = {:?}", e);
                return;
            }
        };

        s2.write_all(&buf[0..n]).await.expect("cant open");
    }
}

async fn handel_connection(mut socket: TcpStream) {
    let mut buf = [0; 4096];
    // In a loop, read data from the socket and write the data back.

    let n = match socket.read(&mut buf).await {
        // socket closed
        Ok(n) if n == 0 => return,
        Ok(n) => n,
        Err(e) => {
            eprintln!("failed to read from socket; err = {:?}", e);
            return;
        }
    };
    let mut server;
    //utf8编码 获取协议
    let req = String::from_utf8_lossy(&buf).to_string();
    let _data: Vec<&str> = req.split(" ").collect();
    //https
    if _data[0] == "CONNECT" {
        server = TcpStream::connect(_data[1]).await.expect("cant open");
        socket
            .write_all(b"HTTP/1.0 200 Connection Established\r\n\r\n").await
        ;
    } else {
        //http
        let _data: Vec<&str> = req.split("\r\n").collect();
        let mut host = String::new();
        for line in _data {
            let v: Vec<&str> = line.split(": ").collect();
            if v[0].eq_ignore_ascii_case("host") {
                host = v[1].to_string();
                if !v[1].contains(":") {
                    host += ":80";
                }
                break;
            }
        }
        if host.is_empty() {
            return;
        }
        server = TcpStream::connect(host).await.expect("cant open");
        server.write_all(&buf[0..n]);
    }

    copy(&mut socket, &mut server);
    copy(&mut server, &mut socket).await;
}
